package wap.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class BufferedFileWriter {
	private FileChannel channel;
	private final int BUFFER_SIZE = 1024 * 100;
	private ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);

	public BufferedFileWriter(String writeFile) {
		try {
			channel = new FileOutputStream(new File(writeFile)).getChannel();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void write(String str) throws IOException {
		byte[] b = str.getBytes();
		if ((b.length + buffer.position()) >= BUFFER_SIZE) {
			buffer.flip();
			while (buffer.hasRemaining())
				channel.write(buffer);
			buffer.clear();
			buffer.put(b);
		} else {
			buffer.put(b);
		}
	}

	public void flush() throws IOException {
		buffer.flip();
		while (buffer.hasRemaining())
			channel.write(buffer);
		buffer.clear();
	}

	public void close() {
		try {
			if (channel.isOpen())
				channel.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException {
		BufferedFileWriter br = new BufferedFileWriter("D:/test.txt");
		String str = "abcdefg\n";
		int i = 0;
		while (true) {
			if (i > 10000) {
				break;
			}
			br.write(str);
			i++;
		}
		System.out.println();
	}
}
